//
//  RFAdReward.swift
//  RFAds
//
//  Created by Roffa Zhou on 2024/12/26.
//

import Foundation
import GoogleMobileAds


//插页式广告先放这里
public class RFAdReward: NSObject {
    public static let shared = RFAdReward()  //如果不需要单例使用，可以不调用此方法，自己维护对象
    fileprivate var reward: RewardedAd?  //激励广告
    public var adId: String = "ca-app-pub-3940256099942544/1712485313"    //激励广告App id, 默认不传使用测试id

    public var isLoadingAd = false   //是否正在加载广告
    public var isShowingAd = false     //是否正在显示广告，此时开屏页显示在页面中
    public private(set) var loadCount: Int = 0       //app生命周期内，加载广告的次数, 只要发起了load就算一次
    public private(set) var loadedCount: Int = 0       //app生命周期内，加载广告成功的次数
    public private(set) var showCount: Int = 0       //app生命周期内，显示过广告的次数
    
    public func loadRewardedAd(){
        Task {
              do {
                  isLoadingAd = true
                  reward = try await RewardedAd.load(
                    with: adId, request: Request())
                  reward?.fullScreenContentDelegate = self
                  isLoadingAd = false
                  RFAdmobUtils.postRewardLoadedNotif()

              } catch {
                  RFAdmobUtils.postRewardLoadeErrNotif(error as NSError)
                  isLoadingAd = false

                print("Failed to load Reward ad with error: \(error.localizedDescription)")
              }
            }
    }
    @discardableResult
    public func showRewardedAd(_ vc: UIViewController) -> Bool{
        if let ad = self.reward {
            isShowingAd = true
            ad.present(from: vc) {
                //奖励到手
                let reward = ad.adReward
                RFAdmobUtils.postRewardCountNotif(reward.amount.stringValue)
//                print("激励广告结束:\(reward.amount)")
            }
            return true
        } else {
          return false
        }
    }
    ///是否有已加载成功，但是未显示的广告
    public func hasLoaded() -> Bool {
        return reward != nil
    }
}

extension RFAdReward:  FullScreenContentDelegate {
    public func adWillPresentFullScreenContent(_ ad: FullScreenPresentingAd) {
        showCount += 1
        RFAdmobUtils.postRewardShowedNotif()
        print("激励广告已显示")

    }
    public func adDidDismissFullScreenContent(_ ad: FullScreenPresentingAd) {
        reward = nil
        isShowingAd = false
        RFAdmobUtils.postRewardDismissNotif()
        print("激励广告已关闭")
        
    }
    public func adWillDismissFullScreenContent(_ ad: FullScreenPresentingAd) {
        RFAdmobUtils.postRewardWillDismissNotif()
        print("激励广告将关闭")

    }
    public func ad(
      _ ad: FullScreenPresentingAd,
      didFailToPresentFullScreenContentWithError error: Error
    ) {
    
      isShowingAd = false
        reward = nil
        RFAdmobUtils.postRewardShowErrNotif(error as NSError)

    }

}

